#requires -version 2


<# todos:
About box
Status line
markup for load tutorial
----
layout via XAML
#>

Import-module wpk

Function txt2flow
{
    param($fileName)

    $pscode = $false
    $global:code = ""

    switch (Get-Content $fileName) {
        {$_.StartsWith('h1')} { New-Paragraph -TextAlignment Center -LineHeight 3 -FontSize 22 -Background Black -Foreground White $_.Substring(3) }
        {$_.StartsWith('h2')} { New-Paragraph -LineHeight 1 -FontSize 18  $_.Substring(3) }
        {$_.StartsWith('h3')} { New-Paragraph -LineHeight 1 -FontSize 15 -Foreground White -Background Blue -FontWeight bold  -FontStyle italic $_.Substring(3)  }
        {$_.StartsWith('.pscode')} { $pscode = $true }
        {$_.StartsWith('.wpkcode')} { $pscode = $true }
        {$_.StartsWith('.xaml')} { $pscode = $true }

        {$_.StartsWith('.link')} {
            $target = $_.Substring(6)
            New-Paragraph (&{
                New-TextBlock (&{ 
                    New-Hyperlink (&{New-Run $target -FontSize 13}) -NavigateUri $target -On_RequestNavigate { 
                        start $this.NavigateUri 
                    }
                })
            } )   	
        }

        {$_.StartsWith('.epscode')} {
            New-Paragraph {
                New-Button -Height 24 -Content 'ps >' -Tag $global:code -On_Click {
                    $cmd = $window | Get-ChildControl Command
                    $output = $window | Get-ChildControl Output
#                     Write-Host $this
#                     Write-Host "$($this.Tag.gettype()) : $($this.Tag)"
                    $cmd.Text = $this.Tag.Trim()
                    if($cmd.Text) {
                        try {
                            $Output.Text = (Invoke-Expression $cmd.Text -ErrorVariable Global:Err | Out-String -Width 80 )
                        } catch {
                            $Output.Text = $Global:Err[0]
                        }
                    }
                }
            }

            $pscode = $false
            $global:code = ""
        }
        {$_.StartsWith('.ewpkcode')} {
            New-Paragraph {
                    New-Button -Height 24 -Content '-show' -Tag $global:code -On_Click {
                    $cmd = $window | Get-ChildControl Command
                    $output = $window | Get-ChildControl Output
                    #Write-Host $this
                    #Write-Host "$($this.Tag.gettype()) : $($this.Tag)"
                    $cmd.Text = $this.Tag.Trim()
                    if($cmd.Text) {
                        try {
                            $Output.Text = (Invoke-Expression $($cmd.Text + ' -OutputXaml') -ErrorVariable Global:Err | Out-String -Width 80 )
                            Invoke-Expression $($cmd.Text + ' -Show') -ErrorVariable Global:Err

                        } catch {
                            $Output.Text = $Global:Err[0]
                        }
                    }
                }
            }

            $pscode = $false
            $global:code = ""
        }

        {$_.StartsWith('.examl')} {
            #Write-Host "Code: $($global:code)"
            New-Paragraph {
                # this is a workaround to get it back as string and not as control
                $tag = '#' + $global:code
                New-Button -Name 'XMLButton' -Height 24 -Content '-OutputXaml' -Tag $tag -On_Click {
                    $cmd = $window | Get-ChildControl Command
                    $output = $window | Get-ChildControl Output
                    #Write-Host $this
                    #Write-Host "$($this.Tag.gettype()) : $($this.Tag)"
                    $cmd.Text = $this.Tag.substring(1)
                    if($cmd.Text) {
                        try {
                               $a = "New-Window {
`@`"
$($cmd.Text)
`"`@
} -SizeToContent WidthAndHeight -show -WindowStartupLocation CenterScreen"
                            Write-Host  $a
                            $Output.Text = (Invoke-Expression $a -ErrorVariable Global:Err | Out-String -Width 80 )
                        } catch {
                            $Output.Text = $Global:Err[0]
                        }
                    }
                 }
            }

            $pscode = $false
            $global:code = ""
        }

        default {
            if($pscode) {
                $global:code += "$($_)`r`n"
                # this is a workaround to inhibit inline lineUIContainer
                # I don't know if there is a recommended way
                $line = $_ -split '(<)'
                New-Paragraph -LineHeight 1  -FontFamily "Lucida Console" -FontSize 11 -Inlines $line
            } else {
                New-Paragraph -LineHeight 1 -FontSize 12 -FontWeight Bold $_


            }
        }
    }
}

Function New-Footer {
    New-Border -BorderThickness 2 -BorderBrush Black -Margin 3 -Dock bottom -child {
        New-StackPanel -Orientation Horizontal {
            function ql {$args}

            $list = ql `
                http://trypowershell.codeplex.com             'Try PowerShell Source Code' `
                http://dougfinke.com/blog                     'Development In A Blink' `
                http://pauerschell.blogspot.com               PauerSchell `
                http://powerboots.codeplex.com                PowerBoots `
                http://code.msdn.microsoft.com/PowerShellPack WPK

            while ($key, $value, $list = $list) {
                New-TextBlock -Margin 5 {
                    New-Hyperlink -NavigateUri $key $value -On_RequestNavigate {
                        [Diagnostics.Process]::Start($_.Uri.AbsoluteUri)
                    }
                }
            }
        }
    }
}

# ----------------------------------------------------------------------------------------------------------------

Function TryPowerShell {
    param (
        $fileName=$(throw ''),
        $snapins
    )

    # Conversion to WPK by Bernd Krisio 2010-04-11

    if(-Not(Test-Path $filename)) {
        write-host -ForegroundColor Red "$($filename) not found"
        return
    }

    if($snapins) {
        Add-PSSnapin $snapins -ErrorAction SilentlyContinue
    }

    $global:WindowTitle = "Try PowerShell and WPK"
    $global:targetFileName=$fileName

    New-Window -name wmain -Title $global:WindowTitle -Width 900 -Height 600 -CommandBindings {
        $close = Get-ApplicationCommand -Close
        New-CommandBinding -Command $close -On_Executed {
                        $tabs = $window | Get-ChildControl tabs
                        $tab = $tabs.SelectedItem
                        $tabs.Items.Remove($tab )
                     }
        $null = $close.InputGestures.Add( (new-object System.Windows.Input.KeyGesture W, Control) )             
        New-CommandBinding -Command { Get-ApplicationCommand -Open } -On_Executed {
            $tabs = $window | Get-ChildControl tabs

            $ofd = New-OpenFileDialog
            $ofd.InitialDirectory = $path
            $ofd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"
            if ($ofd.ShowDialog()) {
                $name = Split-path $ofd.FileName -leaf
                $a = new-tabitem -header $name {
                    # New-FlowDocumentReader
                    # New-FlowDocumentScrollViewer
                    # New-RichTextBox
                    # New-FlowDocumentPageViewer
                    New-FlowDocumentReader -Name doc -Row 0 -RowSpan 3 -Column 0 -ViewingMode Scroll -Document {
                        New-FlowDocument -FontFamily Arial -ColumnWidth 300 -IsHyphenationEnabled -IsOptimalParagraphEnabled {
                            txt2flow $ofd.FileName
                        }
                    }
                 }
                 $tabs.Items.Add($a)
                 $a.Focus();
            }
        }
    } -WindowStartupLocation CenterScreen {
    	New-DockPanel  {
#         New-StatusBar -Dock Bottom {
#                 New-StatusBarItem { 
#                     New-textblock 'ToDo'
#                 }
#             }
        	New-Menu -Dock Top {
				New-MenuItem "_File" {
					New-MenuItem -Command Open
					New-MenuItem -Command (Get-ApplicationCommand -Close)
					New-Separator

					$Exit = New-RoutedUICommand -Text Exit -InputGestures $(new-object System.Windows.Input.KeyGesture F4, Alt)
					New-MenuItem -Command $Exit  -CommandBindings  {
						New-CommandBinding -Command {$Exit} -On_Executed {
							$window.close()
						}
					}
				} # Menu File
				New-MenuItem "_Edit" {
					New-MenuItem -Command Undo
					New-MenuItem -Command Redo
					
					New-Separator

					New-MenuItem -Command Cut
					New-MenuItem -Command Copy
					New-MenuItem -Command Paste
					
					New-Separator 
					
					New-MenuItem -Command SelectAll
				}
				New-MenuItem "_View" {
					"ToDo"
				}
				New-MenuItem "_Help" {
					"ToDo About"
				}
        } # Menu
    		New-Footer
    		New-Grid -Columns 400, * {
				new-tabcontrol  -name tabs -column 0 {
					$name = Split-path $global:targetFileName -leaf
					new-tabitem -header $name {
						# New-FlowDocumentReader
						# New-FlowDocumentScrollViewer
						# New-RichTextBox
						# New-FlowDocumentPageViewer
						New-FlowDocumentReader -Name doc -Row 0 -RowSpan 3 -Column 0 -ViewingMode Scroll -Document {
							New-FlowDocument -FontFamily Arial -ColumnWidth 300 -IsHyphenationEnabled -IsOptimalParagraphEnabled {
								#New-Paragraph 'test'
								global:txt2flow $global:targetFileName
							}
						}
					}
				}
				#----
				New-GridSplitter -column 0 -width 2 -Background  Black
				#New-Grid -Rows 50*,Auto,50*,Auto  -column 1{
				New-Grid -Rows *,2,*   -column 1{
					New-TextBox      -Row 0 -Name Command -TextWrapping Wrap -Margin 5 -AcceptsReturn 
					New-GridSplitter -Row 1 -height 2 -Background  Black -HorizontalAlignment Stretch
					New-Grid         -Row 2 -Rows Auto, 50* {
					New-StackPanel   -Row 0 -Orientation Horizontal  {
						New-Button "_Run" -Margin 5 -Height 32 -On_Click {
							$cmd = $window | Get-ChildControl Command
							$output = $window | Get-ChildControl Output
							if ($cmd.Text)
							{
								if (($cmd.Text.trimStart())[0] -eq '<')
								{
									try {
										$a = "New-Window {
`@`"
$($cmd.Text)
`"`@
} -SizeToContent WidthAndHeight -WindowStartupLocation CenterScreen -show"
										Write-Host  $a
										$Output.Text = (Invoke-Expression $a -ErrorVariable Global:Err | Out-String -Width 80 )
									} catch {
										$Output.Text = $Global:Err[0]
									}
								}
								else{
									try {
										$result = (Invoke-Expression $cmd.Text -ErrorVariable Global:Err)
										Write-Host $result.gettype()
										if ( ! $result)
										{
										}
										elseif ( $result -is [string])
										{
										$Output.Text = ($result | Out-String -Width 80 )
										}
										elseif ($result -is [System.Windows.Window])
										{
											$result.ShowDialog()
										}
										else
										{
											$Output.Text = (Invoke-Expression $($cmd.Text + ' -OutputXaml') -ErrorVariable Global:Err | Out-String -Width 80 )
											#$Output.Text = $result.gettype()
											New-Window {
												$result
											} -SizeToContent WidthAndHeight -WindowStartupLocation CenterScreen -Show
										}

									} catch {
										$Output.Text = $Global:Err[0]
										$Output.Text = $result.gettype()
									}
								}
							}
						}
						New-Button "_Clear" -Margin 5 -Height 32 -On_Click {
							$cmd = $window | Get-ChildControl Command
							$cmd.Text = ""
						}
						New-Button "_Clear All" -Margin 5 -Height 32 -On_Click {
							$cmd = $window | Get-ChildControl Command
							$output = $window | Get-ChildControl Output
							$cmd.Text = ""
							$output.Text = ""
						}
					}
					New-TextBox -Row 1 -Name Output -FontFamily 'Lucida Console' -Margin 5 -IsReadOnly -VerticalScrollBarVisibility Auto -HorizontalScrollBarVisibility Auto 
					}
				}
      		}                                   # Grid 1
    	}         								# DockPanel
  } -show         								# Window
}

$path = Split-Path (Resolve-Path $MyInvocation.InvocationName)

TryPowerShell (Join-Path $path WPK_1.txt)
#TryPowerShell (Join-Path $path TryPowershellSql.txt) -Snapins ('SqlServerCmdletSnapin100', 'SqlServerProviderSnapin100')